/**
 * vuex状态管理，推荐 actions -> mutations -> state
 */
import { createStore } from 'vuex'
import { setToken, removeToken } from '@/utils/token'
import User from '@/api/sys/user'

const store = createStore({
  state: {
    token: '',
    userInfo: {}
  },

  getters: {
    token: (state) => state.token,
    userInfo: (state) => state.userInfo,

    /**
     * userInfo是否存在
     */
    existUserInfo: (state) => {
      return !!state.userInfo.username
    }
  },

  actions: {
    /**
     * 保存登录Token
     */
    login({ commit }, token) {
      commit('SET_TOKEN', token)
      setToken(token)
    },

    /**
     * 获取用户信息
     */
    getUserInfo({ commit }) {
      User.get().then(({ result }) => {
        commit('SET_USERINFO', result)
      })
    },

    async logout({ commit }) {
      await User.logout()
      removeToken()
      commit('SET_TOKEN', null)
    }
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USERINFO: (state, userInfo) => {
      state.userInfo = userInfo
    }
  }
})

export default store
